import React, { FunctionComponent, useState } from 'react'
import { render } from 'react-dom'
import jsonToFormData from 'json-form-data'

let Root: FunctionComponent = props => {
    let [csv, setCsv] = useState("地区,gb\r\n北京,110000")
    let [cookie, setCookie] = useState("")
    function sendCookie(value: string) {
        fetch(`/iportal/setcookie/${value}`).then(() => {
            setCookie(value);
        })
    }
    function postCsv() {
        let fileName = `test_${Math.random()}.csv`
        fetch('/iportal/web/mycontent/datas.json', {
            body: JSON.stringify({ fileName: fileName, type: "CSV" }),
            method: "POST"
        }).then(r => r.json()).then((json: { childID: string }) => {
            let formData: FormData = jsonToFormData({
                newfile: new File(["\ufeff" + csv], fileName) // \ufeff 是 bom。excel打开csv的时候认utf8-bom，不认utf-8
            })
            fetch(`/iportal/web/mycontent/datas/${json.childID}/upload.rjson`, {
                method: "POST",
                body: formData
            }).then(r => r.text()).then(txt => alert(`${fileName}\r\n${txt}`))
        })
    }
    return (
        <div>
            <div>
                <div>
                    登录<a target="_blank" href="https://itest.supermapol.com">itest</a>获取cookie(形如 JSESSIONID=D5D6C8029D08DE04512697F72A261A1B-n1)。<br/>
                    填入下方。
            </div>
                <div>
                    <label>cookie:</label><input onChange={e => sendCookie(e.target.value)} value={cookie}></input></div>
            </div>
            <div>
                <div>
                    <textarea onChange={e => setCsv(e.target.value)} value={csv}></textarea></div>
                <div>
                    <button disabled={cookie.trim().length == 0} onClick={postCsv}>添加</button></div>
            </div>
        </div>
    )
}

let root = document.getElementById("root");
if (root == null) {
    throw "null root element"
} else {
    render(<Root />, root);
}